package com.hdu.other.nestedRecursion;


import java.util.ArrayList;
import java.util.List;

public class lc227 {
    class Solution {
        public int calculate(String s) {
            List<Integer> numbers = new ArrayList<>();
            List<Character> ops = new ArrayList<>();
            int cur = 0;
            int len = s.length();
            for (int i = 0; i < len; i++) {
                char c = s.charAt(i);
                if (c == ' ') {
                    continue;
                } else if (c >= '0' && c <= '9') {
                    cur = cur * 10 + c - '0';
                } else {
                    put(
                            numbers,
                            ops,
                            cur,
                            c
                    );
                    cur = 0;
                }
            }
            put(numbers, ops, cur, '+');
            return compute(numbers, ops);
        }

        int compute(List<Integer> numbers, List<Character> ops) {
            int ans = numbers.get(0);
            for (int i = 1; i < numbers.size(); i++) {
                ans += ops.get(i - 1) == '+' ? numbers.get(i) : -numbers.get(i);
            }
            return ans;
        }

        void put(List<Integer> numbers, List<Character> ops, int num, char op) {
            int len = numbers.size();
            if (len == 0 || ops.get(len - 1) == '+' || ops.get(len - 1) == '-') {
                numbers.add(num);
                ops.add(op);
            } else {
                int lastNumber = numbers.get(len - 1);
                char lastOp = ops.get(len - 1);
                if (lastOp == '*') {
                    numbers.set(len - 1, lastNumber * num);
                } else {
                    numbers.set(len - 1, lastNumber / num);
                }
                ops.set(len - 1, op);
            }
        }
    }
}
